package cn.elead.chaos.sso.server.web.system.controller;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.elead.chaos.core.enums.BusinessType;
import cn.elead.chaos.excel.ExcelUtil;
import cn.elead.chaos.framework.monitor.operlog.Log;
import cn.elead.chaos.framework.properties.ChaosProperties;
import cn.elead.chaos.framework.web.global.ApiAssert;
import cn.elead.chaos.framework.web.global.ErrorCodeEnum;
import cn.elead.chaos.mybatils.web.controller.BaseController;
import cn.elead.chaos.mybatils.web.page.TableDataInfo;
import cn.elead.chaos.shiro.util.ShiroUtils;
import cn.elead.chaos.sso.server.constants.UserConstants;
import cn.elead.chaos.sso.server.utli.Current;
import cn.elead.chaos.sso.server.web.login.service.RedisSaveService;
import cn.elead.chaos.sso.server.web.system.domain.SysUser;
import cn.elead.chaos.sso.server.web.system.service.ISysPostService;
import cn.elead.chaos.sso.server.web.system.service.ISysRoleService;
import cn.elead.chaos.sso.server.web.system.service.ISysUserService;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
	private String prefix = "system/user";

	@Autowired
	private ISysUserService userService;

	@Autowired
	private ISysRoleService roleService;

	@Autowired
	private ISysPostService postService;

	@Autowired
	private RedisSaveService redisSaveService;

	@Autowired
	private ChaosProperties chaos;

	@Autowired
	private RSA rsa;

	@GetMapping
	@RequiresPermissions("system:user:view")
	public String user() {
		return prefix + "/user";
	}

	@ResponseBody
	@PostMapping("/list")
	// @RequiresPermissions("system:user:list")
	public TableDataInfo<SysUser> list(SysUser user) {
		startPage();
		List<SysUser> list = userService.selectUserList(user);
		if (ObjectUtil.isNotEmpty(list)) {
			for (SysUser sysUser : list) {
				sysUser.setPassword("");
				sysUser.setSalt("");
				sysUser.setCardId("");
				String avatar = sysUser.getAvatar();
				if (ObjectUtil.isNotEmpty(avatar)) {
					sysUser.setAvatar(chaos.getHost() + avatar);
				} else {
					String resourcePath = chaos.getPath().getResourcePath();
					String avatarPath = chaos.getPath().getPrefix().getAvatar();
					int randomInt = RandomUtil.randomInt(50);
					sysUser.setAvatar(chaos.getHost() + resourcePath + avatarPath + "default/" + randomInt + ".jpg");
				}
			}
		}
		return getDataTable(list);
	}

	@ResponseBody
	@PostMapping("/export")
	@RequiresPermissions("system:user:export")
	@Log(title = "用户管理", businessType = BusinessType.EXPORT)
	public String export(SysUser user) {
		List<SysUser> list = userService.selectUserList(user);
		ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
		return util.exportExcel(list, "用户数据");
	}

	@ResponseBody
	@PostMapping("/importData")
	@RequiresPermissions("system:user:import")
	@Log(title = "用户管理", businessType = BusinessType.IMPORT)
	public String importData(MultipartFile file, boolean updateSupport) throws Exception {
		ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
		List<SysUser> userList = util.importExcel(file.getInputStream());
		String operName = ShiroUtils.getSysUser().getLoginName();
		String message = userService.importUser(userList, updateSupport, operName);
		return message;
	}

	@ResponseBody
	@GetMapping("/importTemplate")
	@RequiresPermissions("system:user:view")
	public String importTemplate() {
		ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
		return util.importTemplateExcel("用户数据");
	}

	/**
	 * 根据用户编号获取详细信息
	 */
	@ResponseBody
	public SysUser getInfo(@PathVariable(value = "userId", required = false) String userId) {
		SysUser sysUser = userService.selectUserById(userId);
		if (ObjectUtil.isNotEmpty(sysUser)) {
			sysUser.setPassword("");
			sysUser.setSalt("");
			sysUser.setCardId("");
			sysUser.setAvatar(chaos.getHost() + sysUser.getAvatar());
		}
		return userService.selectUserById(userId);
	}

	/**
	 * 新增用户
	 */
	@GetMapping("/add")
	public String add(ModelMap mmap) {
		mmap.put("roles", roleService.selectRoleAll());
		mmap.put("posts", postService.selectPostAll());
		return prefix + "/add";
	}

	/**
	 * 新增保存用户
	 */
	@ResponseBody
	@PostMapping("/add")
	@RequiresPermissions("system:user:add")
	@Log(title = "用户管理", businessType = BusinessType.INSERT)
	public void addSave(@Validated SysUser user) {
		if (UserConstants.USER_NAME_NOT_UNIQUE == userService.checkLoginNameUnique(user.getLoginName())) {
			ApiAssert.failure(ErrorCodeEnum.BAD_REQUEST.convert("新增用户'" + user.getLoginName() + "'失败，登录账号已存在"));
		} else if (UserConstants.USER_PHONE_NOT_UNIQUE == userService.checkPhoneUnique(user)) {
			ApiAssert.failure(ErrorCodeEnum.BAD_REQUEST.convert("新增用户'" + user.getLoginName() + "'失败，手机号码已存在"));
		} else if (UserConstants.USER_EMAIL_NOT_UNIQUE == userService.checkEmailUnique(user)) {
			ApiAssert.failure(ErrorCodeEnum.BAD_REQUEST.convert("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在"));
		}
		String password = HexUtil.encodeHexStr(rsa.encrypt(user.getPassword(), KeyType.PrivateKey));
		user.setPassword(password);
		user.setCreateBy(ShiroUtils.getLoginName());
		userService.insertUser(user);
	}

	/**
	 * 修改用户
	 */
	@GetMapping("/edit/{userId}")
	public String edit(@PathVariable("userId") String userId, ModelMap mmap) {
		mmap.put("user", userService.selectUserById(userId));
		mmap.put("roles", roleService.selectRolesByUserId(userId));
		mmap.put("posts", postService.selectPostsByUserId(userId));
		return prefix + "/edit";
	}

	/**
	 * 修改保存用户
	 */
	@ResponseBody
	@PostMapping("/edit")
	@RequiresPermissions("system:user:edit")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	public void editSave(@Validated SysUser user) {
		userService.checkUserAllowed(user);
		if (UserConstants.USER_PHONE_NOT_UNIQUE == userService.checkPhoneUnique(user)) {
			ApiAssert.failure(ErrorCodeEnum.BAD_REQUEST.convert("修改用户'" + user.getLoginName() + "'失败，手机号码已存在"));
		} else if (UserConstants.USER_EMAIL_NOT_UNIQUE == userService.checkEmailUnique(user)) {
			ApiAssert.failure(ErrorCodeEnum.BAD_REQUEST.convert("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在"));
		}
		user.setUpdateBy(ShiroUtils.getLoginName());
		userService.updateUser(user);
	}

	@GetMapping("/resetPwd/{userId}")
	@RequiresPermissions("system:user:resetPwd")
	@Log(title = "重置密码", businessType = BusinessType.UPDATE)
	public String resetPwd(@PathVariable("userId") String userId, ModelMap mmap) {
		mmap.put("user", userService.selectUserById(userId));
		return prefix + "/resetPwd";
	}

	@ResponseBody
	@PostMapping("/resetPwd")
	@RequiresPermissions("system:user:resetPwd")
	@Log(title = "重置密码", businessType = BusinessType.UPDATE)
	public void resetPwdSave(SysUser user) {
		userService.checkUserAllowed(user);
		String password = user.getPassword();
		password = HexUtil.encodeHexStr(rsa.encrypt(password, KeyType.PrivateKey));
		user.setPassword(password);
		if (userService.resetUserPwd(user) > 0) {
			if (Current.getUserId() == user.getUserId()) {
				Current.bind(userService.selectUserById(user.getUserId()));
			}
			redisSaveService.saveSysUserToRedis(user.getUserId(), user);
		}
	}

	@ResponseBody
	@PostMapping("/remove")
	@RequiresPermissions("system:user:remove")
	@Log(title = "用户管理", businessType = BusinessType.DELETE)
	public void remove(String ids) throws Exception {
		userService.deleteUserByIds(ids);
	}

	/**
	 * 校验用户名
	 */
	@ResponseBody
	@PostMapping("/checkLoginNameUnique")
	public int checkLoginNameUnique(SysUser user) {
		return userService.checkLoginNameUnique(user.getLoginName());
	}

	/**
	 * 校验手机号码
	 */
	@ResponseBody
	@PostMapping("/checkPhoneUnique")
	public int checkPhoneUnique(SysUser user) {
		return userService.checkPhoneUnique(user);
	}

	/**
	 * 校验email邮箱
	 */
	@ResponseBody
	@PostMapping("/checkEmailUnique")
	public int checkEmailUnique(SysUser user) {
		return userService.checkEmailUnique(user);
	}

	/**
	 * 用户状态修改
	 */
	@ResponseBody
	@PostMapping("/changeStatus")
	@RequiresPermissions("system:user:edit")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	public void changeStatus(SysUser user) {
		userService.checkUserAllowed(user);
		userService.changeStatus(user);
	}
}